<template>
  <div>
    <el-dialog
      v-model="execute"
      :close-on-click-modal="false"
      width="90%"
      @close="closeDialog"
    >
      <div class="exeResult">
        <!--计算结果折线图-->
        <el-row v-if="respData.fit" class="main">
          <!--//(respData?.key ?? []).includes('fit')-->
          <el-col :span="24">
            <div id="chart"></div>
          </el-col>
        </el-row>
        <!--表格区域-->
        <el-row class="tableBodys">
          <el-card
            v-for="(k, i) in respData.key"
            :key="k"
            :style="{ border: 'solid' + '  1px  ' + titleColor[i] }"
            class="panel"
          >
            <div :style="{ backgroundColor: titleColor[i] }" class="title">
              {{ getTitle(respData[k]) }}
            </div>
            <el-table :data="getBody(respData[k])" stripe style="width: 100%">
              <!-- <template #empty>暂无数据111</template> -->
              <el-table-column
                v-for="item in getHead(respData[k])"
                :key="item[0]"
                :label="item[1]"
                :prop="item[0]"
              />
              <template #empty><span></span></template>
            </el-table>
          </el-card>
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import echarts from "@/utils/echarts";
import {
  computed,
  defineEmits,
  nextTick,
  onBeforeMount,
  onMounted,
  ref,
  watch,
} from "vue";
import { ElMessage } from "element-plus";

const emit = defineEmits(["close"]);

const execute = ref(false);
/*
let respData = {
  /!*  key: ['tab0', 'tab1', 'classStat', 'exp', 'fit'],
  parmDep: [2],
  parmIndep: [5],
  exp: [
    ["拟合模型"],
    ["价格= 9 + 1*(数量-`数量) + 0 *(数量-`数量)^2"],
  ],
  fit: [
    ["拟合曲线"],
    ["序号", "名称", "价格", "上架日期", "原产地", "数量", "类型", "详情", "拟合值", "残差"],
    ["1", "1", "5", "09/19/2023", "1", "200", "水果", "1", " 5 ", " 0 "],
    ["2", "2", "6", "08/01/2023", "1", "201", "水果", "2", " 6 ", " 0 "],
    ["3", "3", "7", "08/02/2023", "1", "202", "水果", "3", " 7 ", " 0 "],
    ["4", "4", "8", "08/03/2023", "1", "203", "水果", "4", " 8 ", " 0 "],
    ["5", "5", "9", "08/04/2023", "1", "204", "蔬菜", "5", " 9 ", " 0 "],
    ["6", "6", "10", "08/05/2023", "1", "205", "水果", "6", " 10 ", " 0 "],
    ["7", "7", "11", "08/06/2023", "1", "206", "蔬菜", "7", " 11 ", " 0 "],
    ["8", "8", "12", "08/07/2023", "1", "207", "水果", "8", " 12 ", " 0 "],
    ["9", "9", "13", "08/08/2023", "1", "208", "肉类", "9", " 13 ", " 0 "],
  ],
  tab0: [
    ['分类0'],
    ['序号', '名称', '价格', '上架日期', '原产地', '数量', '类型', '详情'],
    ["1", "1", "5", "09/19/2023", "1", "200", "水果", "1"],
    ["2", "2", "6", "08/01/2023", "1", "201", "水果", "2"],
    ["3", "3", "7", "08/02/2023", "1", "202", "水果", "3"],
    ["4", "4", "8", "08/03/2023", "1", "203", "水果", "4"],
  ],
  tab1: [
    ["分类1"],
    ["序号", "名称", "价格", "上架日期", "原产地", "数量", "类型", "详情"],
    ["5", "5", "9", "08/04/2023", "1", "204", "蔬菜", "5"],
    ["6", "6", "10", "08/05/2023", "1", "205", "水果", "6"],
    ["7", "7", "11", "08/06/2023", "1", "206", "蔬菜", "7"],
    ["8", "8", "12", "08/07/2023", "1", "207", "水果", "8"],
    ["9", "9", "13", "08/08/2023", "1", "208", "肉类", "9"],
  ],
  classStat: [
    ["分类类别"],
    ["分类", "数量", "占比"],
    ["0#", 4, " 44 %"],
    ["1#", 5, " 55 %"],
  ]*!/
};
*/
const exeResultdialog = defineProps({
  exeResultdialog: Boolean,
  queryParams: Object,
});
watch(
  () => exeResultdialog.exeResultdialog,
  (newValue, o) => {
    execute.value = newValue;
    if (!newValue) {
      chart.dispose();
    }
  }
);

watch(
  () => exeResultdialog.queryParams,
  (newValue, oldValue) => {
    // console.log(newValue);
    getChartData(newValue);
  }
);
const respData = computed(() => {
  console.log(exeResultdialog.queryParams, "穿的值");
  if (exeResultdialog.queryParams) {
    const data = exeResultdialog.queryParams;
    // debugger;
    getChartData(data.fit, data.parmIndep[0], data.parmDep[0]);
    nextTick(() => {
      init();
    });
    return data;
  }
});

/*
watch(respData, async (newValue) => {


  /!*  console.log(option,'option')
    await nextTick(() => {
      if (chart) {
        chart.setOption(option);
      }
    })*!/
})
*/

/*async function queryExecuteParams(params) {
  try {
    const result = await executeAlgorithm(params);
    const respData = result.respData
    getChartData(respData.fit, respData.parmIndep[0], respData.parmDep[0]);
    await nextTick(() => {
      init();
    })
  } catch (e) {
    console.log(e)
  }
}*/

function getTitle(tableArr) {
  if (!tableArr || !tableArr[0]) return showMsg("结果表名不存在");
  return tableArr[0][0];
}

const titleColor = [
  "#FF6A6A99",
  "#87CEEB",
  "#90EE90",
  "#D8BFD8",
  "#FFC0CB",
  "#FFE7BA",
  "#EEE5DE",
];

// echart曲线图，不能使用响应式，会报错
let chart = null;

let xAxisJSon = [];
let seriesFitDataJSon = [];
let seriesFactDataJSon = [];
let seriesResidualDataJSon = [];

function getChartData(tableArr, x, y) {
  xAxisJSon = [];
  seriesFitDataJSon = [];
  seriesFactDataJSon = [];
  seriesResidualDataJSon = [];
  console.log(tableArr);

  // if (!tableArr || !tableArr[2]) return showMsg("结果表数据不存在");
  x = 0;

  for (let i = 2; i < tableArr.length; i++) {
    xAxisJSon.push(tableArr[i][x]);
    let len = tableArr[i].length;
    if (tableArr[i].length > 2) seriesFitDataJSon.push(tableArr[i][len - 2]);
    seriesFactDataJSon.push(tableArr[i][y]);
    if (tableArr[i].length > 1)
      seriesResidualDataJSon.push(tableArr[i][len - 1]);
  }
  console.log(xAxisJSon, "=====xAxisJSon");

  option.xAxis[0].data = xAxisJSon;
  option.series[0].data = seriesFactDataJSon;
  option.series[1].data = seriesFitDataJSon;
  option.series[2].data = seriesResidualDataJSon;

  console.log(option, "=====option");
}

const option = {
  title: {
    text: "拟合",
    x: "center",
  },
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b} : {c}",
  },
  legend: {
    data: ["原始值", "拟合值", "残差"],
    x: "left",
  },
  toolbox: {
    show: true,
    feature: {
      mark: {
        show: true,
      },
      dataView: {
        show: true,
        readOnly: false,
      },
      magicType: {
        show: true,
        type: ["line", "bar"],
      },
      restore: {
        show: true,
      },
      saveAsImage: {
        show: true,
      },
    },
  },
  dataZoom: {
    show: true,
    realtime: true,
    start: 0,
    end: 100,
  },
  xAxis: [
    {
      name: "",
      type: "category",
      boundaryGap: false,
      axisLine: {
        onZero: false,
      },
      data: [],
    },
  ],
  yAxis: [
    {
      name: "值",
      type: "value",
    },
    {
      name: "残差",
      type: "value",
    },
  ],
  series: [
    {
      name: "原始值",
      type: "line",
      data: seriesFactDataJSon,
      markPoint: {
        label: {
          show: true,
        },
        data: [
          {
            type: "max",
            name: "最大值",
          },
          {
            type: "min",
            name: "最小值",
          },
        ],
      },
      markLine: {
        data: [
          {
            type: "average",
            name: "平均值",
          },
        ],
      },
    },
    {
      name: "拟合值",
      type: "line",
      data: seriesFitDataJSon,
      markPoint: {
        data: [
          {
            type: "max",
            name: "最大值",
          },
          {
            type: "min",
            name: "最小值",
          },
        ],
      },
      markLine: {
        data: [
          {
            type: "average",
            name: "平均值",
          },
        ],
      },
    },
    {
      name: "残差",
      type: "line",
      yAxisIndex: 1,
      data: seriesResidualDataJSon,
      markPoint: {
        data: [
          {
            type: "max",
            name: "最大值",
          },
          {
            type: "min",
            name: "最小值",
          },
        ],
      },
      markLine: {
        data: [
          {
            type: "average",
            name: "平均值",
          },
        ],
      },
    },
  ],
};

function getHead(tableArr) {
  if (!tableArr || !tableArr[1]) return showMsg("结果表头不存在");

  let map = [];
  for (let i = 0; i < tableArr[1].length; i++) {
    let prop = [];
    prop.push("p" + i);
    prop.push(tableArr[1][i]);
    map.push(prop);
  }
  return map;
}

function closeDialog() {
  emit("close", false);
}

function getBody(tableArr) {
  if (!tableArr || !tableArr[1]) return showMsg("结果表数据不存在");

  let props = [];
  console.log(tableArr);
  for (let i = 2; i < tableArr.length; i++) {
    let prop = {};
    for (let j = 0; j < tableArr[i].length; j++) {
      // console.log(prop["p" + j]);//数据中带""?"改成-
      prop["p" + j] = tableArr[i][j];
      if (prop["p" + j] == "?" || prop["p" + j] == "NaN") {
        prop["p" + j] = "-";
      }
    }
    props.push(prop);
  }
  return props;
}

// onBeforeMount(() => {
/*  respData = JSON.parse(localStorage.getItem("respData"));
    console.log(respData,'respData')
    /!*  respData = route.respData
      console.log(route.respData,'respData')*!/
    if (respData) {
      getChartData(respData.fit, respData.parmIndep[0], respData.parmDep[0]);
    }*/
// });

function init() {
  const dom = document.getElementById("chart");

  if (dom) {
    //加载视图
    chart = echarts.init(dom);
    chart.setOption(option, true);
    console.log(option, "渲染的option");
    // 修改卡牌的颜色
    const es = document.getElementsByClassName("el-card__header");
    let i = 0;
    for (let e of es) {
      e.style.backgroundColor = titleColor[i++];
    }

    // 隐表格长度少于2的空块
    const tbs = document.getElementsByClassName("el-table__body-wrapper");
    for (let j = 0; j < (respData?.key ?? []).length; j++) {
      if (respData[respData.key[j]].length <= 2) tbs[j].style.display = "none";
    }
  }
}

onMounted(() => {
  init();
});

function showMsg(message, type = "error") {
  ElMessage({ message, type });
}
</script>

<style lang="scss" scoped>
.exeResult {
  width: 100%;
  height: 660px;
  overflow: hidden auto;

  .tableBodys {
    :deep(.el-table__empty-block) {
      display: none !important;
    }
  }

  .title {
    padding: 15px;
    color: #fff;
  }

  #chart {
    width: 100%;
    height: 350px;
  }

  .panel {
    width: 100%;
    margin: 10px;
  }

  :deep(.el-card__header) {
    padding: 15px;
    background-color: green;
  }

  :deep(.el-card__body) {
    padding: 0;
  }
}

:deep(.el-dialog__header) {
  padding-bottom: 20px;
}
</style>